package com.wandousoushu.jiusen.ui.info

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.lifecycle.Observer
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions.bitmapTransform
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.R.*
import com.wandousoushu.jiusen.base.VMBaseActivity
import com.wandousoushu.jiusen.booksource.bean.BookChapter
import com.wandousoushu.jiusen.booksource.constant.Theme
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.help.BlurTransformation
import com.wandousoushu.jiusen.help.ImageLoader
import com.wandousoushu.jiusen.help.IntentDataHelp
import com.wandousoushu.jiusen.lib.theme.backgroundColor
import com.wandousoushu.jiusen.lib.theme.bottomBackground
import com.wandousoushu.jiusen.ui.book.changesource.ChangeSourceDialog
import com.wandousoushu.jiusen.ui.book.chapterlist.ChapterListActivity
import com.wandousoushu.jiusen.ui.book.read.ReadBookActivity
import com.wandousoushu.jiusen.ui.login.LoginActivity
import com.wandousoushu.jiusen.ui.widget.image.CoverImageView
import com.wandousoushu.jiusen.util.getViewModel
import com.wandousoushu.jiusen.util.gone
import com.wandousoushu.jiusen.util.visible
import kotlinx.android.synthetic.main.activity_book_info.*
import org.jetbrains.anko.sdk27.listeners.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast


class BookInfoActivity :
    VMBaseActivity<BookInfoViewModel>(layout.activity_book_info, theme = Theme.Dark),
    ChapterListAdapter.CallBack,
        ChangeSourceDialog.CallBack{

    private val requestCodeChapterList = 568
    private val requestCodeSourceEdit = 562
    private val requestCodeRead = 432

    override val viewModel: BookInfoViewModel
        get() = getViewModel(BookInfoViewModel::class.java)

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        arc_view.setBgColor(backgroundColor)
        ll_info.setBackgroundColor(backgroundColor)
        scroll_view.setBackgroundColor(backgroundColor)
        fl_action.setBackgroundColor(bottomBackground)
        viewModel.bookData.observe(this, Observer { showBook(it) })
        viewModel.chapterListData.observe(this, Observer { upLoading(false, it) })
        viewModel.initData(intent)
        initOnClick()
    }

    private fun showBook(book: Book) {
        showCover(book)
        tv_name.text = book.name
        tv_author.text = getString(string.author_show, book.getRealAuthor())
        tv_origin.text = getString(string.origin_show, book.originName)
        tv_lasted.text = getString(string.lasted_show, book.latestChapterTitle)
        tv_toc.text = getString(string.toc_s, getString(string.loading))
        tv_intro.text = book.getDisplayIntro()
        upTvBookshelf()
        upImageBookMark()
        val kinds = book.getKindList()
        if (kinds.isEmpty()) {
            lb_kind.gone()
        } else {
            lb_kind.visible()
            lb_kind.setLabels(kinds)
        }
    }

    private fun showCover(book: Book) {
        iv_cover.load(book.getDisplayCover(), book.name, book.author)
        ImageLoader.load(this, book.getDisplayCover())
            .transition(DrawableTransitionOptions.withCrossFade(1500))
            .thumbnail(defaultCover())
            .apply(bitmapTransform(BlurTransformation(this, 25)))
            .into(bg_book)  //模糊、渐变、缩小效果
    }

    private fun defaultCover(): RequestBuilder<Drawable> {
        return ImageLoader.load(this, CoverImageView.defaultDrawable)
            .apply(bitmapTransform(BlurTransformation(this, 25)))
    }

    private fun upLoading(isLoading: Boolean, chapterList: List<BookChapter>? = null) {
        when {
            isLoading -> {
                tv_toc.text = getString(string.toc_s, getString(string.loading))
            }
            chapterList.isNullOrEmpty() -> {
                tv_toc.text = getString(string.toc_s, getString(string.error_load_toc))
            }
            else -> {
                viewModel.bookData.value?.let {
                    if (it.durChapterIndex < chapterList.size) {
                        tv_toc.text =
                            getString(string.toc_s, chapterList[it.durChapterIndex].title)
                    } else {
                        tv_toc.text = getString(string.toc_s, chapterList.last().title)
                    }
                }
            }
        }
    }

    private fun upTvBookshelf() {
        if (viewModel.inBookshelf) {
            tv_shelf.text = getString(string.remove_from_bookshelf)
        } else {
            tv_shelf.text = getString(string.add_to_shelf)
        }
    }

    private fun upImageBookMark() {
        if (viewModel.inBookMark) {
            iv_bookmark.setImageDrawable(getDrawable(drawable.ic_star))
            //tv_shelf.text = getString(R.string.remove_from_bookshelf)
        } else {
            iv_bookmark.setImageDrawable(getDrawable(drawable.ic_star_border))
            //tv_shelf.text = getString(R.string.add_to_shelf)
        }
    }

    private fun initOnClick() {
//        iv_cover.onClick {
//            viewModel.bookData.value?.let {
//                ChangeCoverDialog.show(supportFragmentManager, it.name, it.author)
//            }
//        }
        tv_read.onClick {
            viewModel.bookData.value?.let {
                readBook(it)
            }
        }
        tv_shelf.onClick {
            if(MyApplication.instance.isLogin){
                if (viewModel.inBookshelf) {
                    deleteBookShelf()
                    toast(R.string.del_success)
                } else {
                    viewModel.addToBookshelf {
                        upTvBookshelf()
                        toast(R.string.add_success)
                    }
                }
            }else{
                startActivity<LoginActivity>()
            }
        }
        tv_toc_view.onClick {
            if (!viewModel.inBookshelf) {
                viewModel.saveBook {
                    viewModel.saveChapterList {
                        openChapterList()
                    }
                }
            } else {
                openChapterList()
            }
        }
        iv_bookmark.onClick {
            if (MyApplication.instance.isLogin){
                if(viewModel.inBookMark){
                    deleteBookMark()
                    toast("取消收藏成功")
                }else{
                    viewModel.addToBookmark {
                        upImageBookMark()
                        toast("收藏成功")
                    }
                }
            }else{
                startActivity<LoginActivity>()
            }
        }
//        tv_author.onClick {
//            startActivity<SearchActivity>(Pair("key", viewModel.bookData.value?.author))
//        }
//        tv_name.onClick {
//            startActivity<SearchActivity>(Pair("key", viewModel.bookData.value?.name))
//        }
    }

    @SuppressLint("InflateParams")
    private fun deleteBookShelf() {
        viewModel.bookData.value?.let {
                viewModel.delBookShlef {
                    upTvBookshelf()
                }
        }
    }

    private fun deleteBookMark() {
        viewModel.bookData.value?.let {
            viewModel.delBookMark {
                upImageBookMark()
            }
        }
    }

    private fun openChapterList() {
        if (viewModel.chapterListData.value.isNullOrEmpty()) {
            toast(string.chapter_list_empty)
            return
        }
        viewModel.bookData.value?.let {
            startActivityForResult<ChapterListActivity>(
                requestCodeChapterList,
                Pair("bookUrl", it.bookUrl)
            )
        }
    }

    private fun readBook(book: Book) {
        if (!viewModel.inBookshelf) {
            viewModel.saveBook {
                viewModel.saveChapterList {
                    startReadActivity(book)
                }
            }
        } else {
            viewModel.saveBook {
                startReadActivity(book)
            }
        }
    }

    private fun startReadActivity(book: Book) {
        startActivityForResult<ReadBookActivity>(
                requestCodeRead,
                Pair("bookUrl", book.bookUrl),
                Pair("inBookshelf", viewModel.inBookshelf),
                Pair("key", IntentDataHelp.putData(book))
            )
//        when (book.type) {
//            BookType.audio -> startActivityForResult<AudioPlayActivity>(
//                requestCodeRead,
//                Pair("bookUrl", book.bookUrl),
//                Pair("inBookshelf", viewModel.inBookshelf)
//            )
//            else -> startActivityForResult<ReadBookActivity>(
//                requestCodeRead,
//                Pair("bookUrl", book.bookUrl),
//                Pair("inBookshelf", viewModel.inBookshelf),
//                Pair("key", IntentDataHelp.putData(book))
//            )
//        }
    }

    override val oldBook: Book?
        get() = viewModel.bookData.value

    override fun changeTo(book: Book) {
        upLoading(true)
        viewModel.changeTo(book)
    }

    override fun openChapter(chapter: BookChapter) {
        if (chapter.index != viewModel.durChapterIndex) {
            viewModel.bookData.value?.let {
                it.durChapterIndex = chapter.index
                it.durChapterPos = 0
                readBook(it)
            }
        }
    }

    override fun durChapterIndex(): Int {
        return viewModel.durChapterIndex
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
//            requestCodeSourceEdit ->
//                if (resultCode == Activity.RESULT_OK) {
//                    viewModel.upEditBook()
//                }
            requestCodeChapterList ->
                if (resultCode == Activity.RESULT_OK) {
                    viewModel.bookData.value?.let {
                        data?.getIntExtra("index", it.durChapterIndex)?.let { index ->
                            if (it.durChapterIndex != index) {
                                it.durChapterIndex = index
                                it.durChapterPos = 0
                            }
                            startReadActivity(it)
                        }
                    }
                } else {
                    if (!viewModel.inBookshelf) {
                        viewModel.delBookShlef()
                    }
                }
            requestCodeRead -> if (resultCode == Activity.RESULT_OK) {
                viewModel.inBookshelf = true
                val bookurl = data!!.getStringExtra("bookurl")
                bookurl?.let {
                    SearchBookManager.GetInstance().getSearchBookByUrl(it)?.let { book ->
                        viewModel.bookData.postValue(book)
                        viewModel.upBook(book)
                    }
                }
                viewModel.addToBookshelf {
                    upTvBookshelf()
                    toast(R.string.add_success)
                }
            }
        }
    }
}